package com.lixuwei.study.tcc.order.dao;

import com.lixuwei.study.tcc.order.entity.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.sql.PreparedStatement;
import java.sql.Statement;

@Repository
public class OrderDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Transactional
    public void saveOrder(Order order) {
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(conn -> {
            PreparedStatement ps =
                    conn.prepareStatement("insert  into tb_order (buyer_id, shop_id, price) values (?,?,?)",
                    Statement.RETURN_GENERATED_KEYS);
            ps.setLong(1, order.getBuyerId());
            ps.setInt(2, order.getShopId());
            ps.setLong(3,order.getPrice());
            return ps;
        }, keyHolder);
        long orderId = keyHolder.getKey().longValue();
        order.setId(orderId);
    }

    public Order getById(Long orderId) {
        return jdbcTemplate.queryForObject("select * from tb_order where id = ?",
                new Object[]{orderId}, Order.class);
    }

    public int updateOrderPaying(Order order) {
        int update = jdbcTemplate.update("update tb_order set pay_status = 1 where order_id =? and pay_status = 0",
                new Object[]{order.getId()});
        return update;
    }
}